package com.csbr.prod.Controller;

import java.util.ArrayList;

import com.csbr.prod.Dao.CollectionDao;
import com.csbr.prod.Dao.TotalImageDao;
import com.csbr.prod.Dao.UsersDao;
import com.csbr.prod.Pojo.CollectionEntity;
import com.csbr.prod.Pojo.TotalImageEntity;
import com.csbr.prod.Pojo.UsersEntity;
import com.csbr.prod.Utils.SendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class CollectionController {

    @Autowired
    private CollectionDao collectionDao;

    @Autowired
    private TotalImageDao totalImageDao;

    @Autowired
    private UsersDao usersDao;

    @RequestMapping("/collection/{username}")
    public SendMessage fun(@PathVariable String username) {
        ArrayList<CollectionEntity> lists = collectionDao.findByUsername(username);
        // ArrayList<Integer> imgs = new ArrayList<Integer>();
        ArrayList<TotalImageEntity> imgs = new ArrayList<TotalImageEntity>();
        for (int i = 0; i < lists.size(); i++) {
            // imgs.add(lists.get(i).getImgid());
            imgs.add((TotalImageEntity) totalImageDao.findById(lists.get(i).getImgid()));
            // System.out.print();
        }
        return SendMessage.Success(imgs);
    }

    @RequestMapping("/addCollection")
    public SendMessage addCollection(@RequestBody CollectionEntity collectionJson) {
        String username = collectionJson.getUsername();
        UsersEntity user = usersDao.findByUsername(username);
        CollectionEntity collect = new CollectionEntity();
        collect.setUsername(username);
        collect.setUserid(user.getId());
        collect.setImgid(collectionJson.getImgid());
        collectionDao.save(collect);
        return SendMessage.Success(collectionDao.findAll());
    }

    @RequestMapping("/deleteCollection")
    public void deleteCollection(@RequestBody CollectionEntity deleteCollection) {
        String username = deleteCollection.getUsername();
        UsersEntity user = usersDao.findByUsername(username);
        // collectionDao.deleteByUsernameAndImgid(deleteCollection.getUsername(), deleteCollection.getImgid());
        CollectionEntity collect = collectionDao.findByUseridAndImgid(user.getId(), deleteCollection.getImgid());
        collectionDao.delete(collect.getId());
    }

}
